package com.mitdy.sg.common.utils;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;


public class StringHelper {

	public static synchronized String makeUUIDWithTime() {
		SimpleDateFormat defaultDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		UUID uuid = UUID.randomUUID();
		String uuidStr = uuid.toString().replaceAll("-", "");
		StringBuilder sb = new StringBuilder();
		String currentTime = defaultDateFormat.format(new Date());
		sb.append(currentTime).append(uuidStr.substring(currentTime.length(), 32));
		return sb.toString();
	}

	public static String getRandomString(int length) {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}
	
	public static String getRandomNum(int length) {
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
	
	public static String fixJsonString(String jsonString) {
	    return jsonString.replaceAll("([a-zA-Z]+):", "\"$1\":");
	}
	
	public static String trimToEmpty(String str) {
	    return StringUtils.trimToEmpty(str);
	}
	
	public static String trim(String str) {
        return StringUtils.trim(str);
    }
	
	public static String collectionToDelimitedString(Collection<String> list, String delim) {
	    return org.springframework.util.StringUtils.collectionToDelimitedString(list, delim);
	}
	
	 public static String getStringFromUrl(String url) {
	        try {
	            URLConnection conn = new URL(url).openConnection();
	            InputStream is = conn.getInputStream();
	            StringBuffer sb = new StringBuffer();

	            byte[] buff = new byte[1024 * 10];
	            int length = 0;
	            while ((length = is.read(buff)) != -1) {
	                sb.append(new String(buff, 0, length, "GBK"));
	            }
	            is.close();
	            return sb.toString();
	        } catch (Exception e) {
	            return "";
	        }
	    }

}
